var uuid = require('uuid')
var config = require('../../../config')
var socketList = {
  "b594eda0-eef3-11e8-b0e8-9bb1d968733b": {
    type: '登录设备',
    user: ['当前socket连接下的用户']
  }
}
module.exports = class extends think.Controller {

  constructor(...arg) {
    super(...arg)
  }

  openAction() {
    this.websocket.ID = this.websocket.ID || uuid.v1()
    this.emit('opend', 'This client opened successfully!')
    return this.success();
  }

  async closeAction() {
    if (!socketList[this.websocket.ID]) return this.success()
    socketList[this.websocket.ID].user = socketList[this.websocket.ID].user || []
    socketList[this.websocket.ID].user.forEach((csid) => {
      this.model('socket').delSocket(csid, socketList[this.websocket.ID].type)
    })
    if (parseInt(socketList[this.websocket.ID].type) === 1002) {
      let userlist = socketList[this.websocket.ID].user
      for (var i = 0; i < userlist.length; i++) {
        let user_id = userlist[i]
        await think.http.get(config.baseUrl + '/login/outline?id=' + user_id)
      }
    }
    return this.success();
  }

  testAction() {
    var data = this.wsData.data
    console.log(data);
    this.emit('test', {
      msg:'服务器返回'
    })
    return this.success()
  }

  connectAction (data) { //客户端请求链接
    // console.log(this.wsData)
    var data = this.wsData.data
    console.log(data)
    // console.log(data)
    // console.log(typeof data)
    // console.log(data.user.id)
    // console.log(data.type)
    var global_user = this.model('user').getuser()
    var socket = this
    if (global_user.state > 0) {
      global_user = global_user.data
    } else {
      global_user = {}
    }
    console.log(global_user);
    if(!(data.user.id in global_user)){
      socket.emit('gologin', '当前用户没有的登录，去登陆！')
        return;
    }
    if(!(data.type in global_user[data.user.id])){
      socket.emit('gologin', '当前客户端没有的登录，去登陆！')
        return;
    }
    global_user[data.user.id][data.type].socket && global_user[data.user.id][data.type].socket.emit('difflogin', '异地登录')
    socket.user_id = data.user.id;
    socket.login_type = data.type;
    global_user[data.user.id][data.type].socket = socket

    this.model('socket').setSocket(data.user.id, data.type, socket)
    socket.emit('re_connect',{status:1,msg:'连接成功',user: data.user, sockerID: this.websocket.ID})
    this.model('user').setUser({
      id:data.user.id,  
      type:data.type,
      data:global_user[data.user.id][data.type]
    })
    return this.success()
  }

  heartbeatAction () { // 响应客户端心跳包
    var data = this.wsData.data
    // console.log('接收数据', data)
    var user = this.model('user').getuser(data)
    // console.log('查找用户', user)
    var user_info
    if (user.state === 1) {
      user_info = user.data
      // console.log('用户详情', user_info)
    } else {
      this.emit('heartbeat', false) 
      return
    }
    var socket = this
    this.emit('heartbeat', user_info.key === data.key)
    return this.success()
  }

  heartbeat_newAction () { // 响应客户端心跳包 新
    var data = this.wsData.data
    var checkResult = []
    if (data.sockerID) this.websocket.ID = data.sockerID
    socketList[this.websocket.ID] = socketList[this.websocket.ID] || {
      type: data.type,
      user: []
    }
    data.userlist.forEach((item) => {
      let inuserList = false
      socketList[this.websocket.ID].user.forEach((item1) => {
        if (parseInt(item1) === parseInt(item.id)) {
          inuserList = true
        }
      })
      if (!inuserList) {
        socketList[this.websocket.ID].user.push(item.id)
      }
      var _data = {
        id: item.id,
        key: item.key,
        type: data.type
      }
      var user = this.model('user').getuser(_data, this)
      var user_info
      if (user.state === 1) {
        user_info = user.data
        this.model('socket').setSocket(item.id, data.type, this)
        checkResult.push({
          id: item.id,
          result: user_info.key == item.key
        })
      } else {
        checkResult.push({
          id: item.id,
          result: false
        })
      }
    })
    this.emit('heartbeat_new', checkResult)
    return this.success()
  }

  messagesyncAction () {
    var data = this.wsData.data
    var global_user = this.model( 'user' ).getuser()
    if ( global_user.state > 0 ) {
      global_user = global_user.data
    } else {
      global_user = {}
    }
    var timeout_list = this.model('user').getTimeoutList()
    if(data.msg.openid in timeout_list){//判断定时器是否已经存在，存在就删除
        clearTimeout(timeout_list[data.msg.openid]);
    }
    if(!data.msg.cs_id in global_user){
        return;
    }
    think.global.loginType.forEach( function( item ) {
      if (item in global_user[data.msg.cs_id] && parseInt(item) !== data.type) {
        global_user[data.msg.cs_id][item].socket.emit( 'sendMsg', data.msg)
      }
    })
    var userinfo = global_user[data.msg.cs_id].user_info;
    if (userinfo.pid != 0) {
      if(userinfo.pid in global_user){
        config.loginType.forEach(function(item){
          if(item in global_user[userinfo.pid]){
            global_user[userinfo.pid][item].socket.emit( 'sendMsg', data.msg)
          }
        })
      }
    }
    return this.success()
  }
}